﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;
using OnlineEducation.Constants;
using OnlineEducation.Controllers;
using OnlineEducation.Data;
using OnlineEducation.Helpers;
using OnlineEducation.Models.ServerAPIModels;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace OnlineEducation.Areas.Controllers
{
    [Area("api")]
    [Route("api/[controller]/[action]")]
    public class BBBCallbackController : BaseController
    {
        private readonly ILogger _logger;
        private readonly ApplicationDbContext _context;
        private readonly IWebHostEnvironment _env;

        public BBBCallbackController(ApplicationDbContext context, ILogger<BBBCallbackController> logger, IWebHostEnvironment env)
        {
            _context = context;
            _logger = logger;
            _env = env;

        }
        [HttpGet]
        public async Task<IActionResult> EndMeetingCallback(string meetingID, string recordingmarks)
        {
            _logger.LogInformation($"Begin to end meeting callback, occurred with meeting id {meetingID}");

            try
            {
                var planitem = await _context.TeachingPlanItems.Where(n => n.MeetingNo == meetingID).FirstOrDefaultAsync();

                if (planitem == null)
                {
                    _logger.LogInformation($"End to end meeting callback, no any plan item found.");

                    return Ok("No any plan item found.");
                }

                planitem.Status = 2;

                _context.Update(planitem);

                _logger.LogInformation($"Update teaching plan item {planitem.Id} status as done successfully.");

                var planID = planitem.TeachingPlanId;

                var plan = _context.TeachingPlans.Include(n=>n.TeachingPlanItems).Where(n => n.Id == planID).FirstOrDefault();

                if (plan != null && plan.TeachingPlanItems.All(n => n.Status == 2))
                {
                    plan.Status = 2;

                    _context.Update(plan);

                    _logger.LogInformation($"Update teaching plan {plan.Id} status as done successfully.");
                }

                await _context.SaveChangesAsync();

                _logger.LogInformation($"End to end meeting callback, occurred with meeting id {meetingID}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.ToString());
            }


            return Ok();

        }

    }
}